<?php
require_once('../../core.inc.php');
require_once('Model/SiteManage.php');
require_once('View/Smarty.php');
require_once('Model/DB.php');
require_once('Model/Validate.php');
require_once('Model/Pager.php');
require_once('Model/Uploader.php');
require_once('Plugin/Staff.php');
require_once('Plugin/Site.php');
//
$sys = new Model_SiteManage();
$sys->checkLogin();
$params = $_REQUEST;
$smarty = new View_Smarty($params);
$staff  = new Model_Staff();
$smarty->assign('staff', $staff);
//サイト一覧取得
$site = new Model_Site();
foreach($site->getList($data=array()) as $id=>$one){
    $site_list[$id] = $one["site_name"];
}
$smarty->assign('site_list', $site_list);
//
if (isset($params['do']) && function_exists('exec_' . $params['do'])){
   $params['op'] = call_user_func('exec_' . $params['do'], &$params, &$smarty, &$staff);
}
if (isset($params['op']) && function_exists('op_' . $params['op'])){
    call_user_func('op_' . $params['op'], $params, &$smarty, &$staff);
}
else{
    call_user_func('op_search', $params, &$smarty, &$staff);
}
//
// 検索・一覧
function op_search($params, &$smarty, &$staff)
{
    if(!isset($params['search'])){
        $params['search'] = array();
        $params['search']['site_id']    = '';
        $params['search']['staff_name'] = '';
        $params['search']['actived']    = '';
    }
    $list = $staff->getList($params['search'], 'id asc');
    $smarty->assign('list', $list);
    $smarty->assign('search', $params['search']);
    $smarty->display('staff/staff_index.html');
}
// 新規登録
function op_regist($params, &$smarty, &$staff)
{
    if (!isset($params['forms'])){
        $forms = array();
        foreach($staff->getFormKeys() as $key){
            $forms[$key] = '';
        }
        $params['forms'] = $forms;
    }
    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params['forms']);
    $smarty->display('staff/staff_form.html');
}
function exec_validate_regist_form(&$params, &$smarty, &$staff)
{
    $err = array();
    if ($staff->validate($params['forms'], $err)){
        return exec_regist_form($params, $smarty, $staff);
    }
    $validate = new Model_Validate();
    $smarty->assign('validate', $validate);
    $smarty->assign('err', $err);
    return 'regist';
}
function exec_regist_form(&$params, &$smarty, &$staff)
{
    if(isset($params['forms']['image_file'])){
        $tmp_image_file = $params['forms']['image_file'];
        unset($params['forms']['image_file']);
    }
    $id = $staff->insert($params['forms']);
    //画像
    if(isset($tmp_image_file))
    {
        $uploader  = new Model_Uploader();
        $cache     = $tmp_image_file[0];
        $base_name = 'image_'.$id;
        $move_to   = $staff->getStaffImageDir();
        $filename  = $uploader->moveCacheImage($cache, $move_to, $base_name);
        $data = array();
        $data['image_file'] = $filename;
        $staff->update($id, $data);
    }
    //権限
    if(isset($params['forms_staff_auth'])){
        auth_register($id, $params['forms_auth']['auth']);
    }
    else{
        auth_register($id);
    }
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=regist_complete&id=' . $id);
    exit();
}
function op_regist_complete($params, &$smarty, &$staff)
{
    $smarty->assign('phase', 'complete');
    if(isset($params['id'])){
        $smarty->assign('id', $params['id']);
        $smarty->assign('forms', array('id' => $params['id']));
    }
    $smarty->assign('message', '登録が完了しました');
    $smarty->display('staff/staff_form.html');
}
// 編集
function op_edit($params, &$smarty, &$staff)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    $db = new Model_DB();
    $id = $params['id'];
    if (!isset($params['forms'])){
        $forms           = $staff->get($id);
        $params['forms'] = $forms;
        if ($forms['image_file'] != ''){
            $params['forms']['image_file']   = array();
            $params['forms']['image_file'][] = $staff->getStaffImageUrl() . $forms['image_file'];
        }
        else{
            $params['forms']['image_file'] = array();
        }
        //権限
        $sql = sprintf("select * from D_STAFF_AUTH where staff_id = '" . $db->escape($id) ."'");
        $db->query($sql);
        while($row = $db->fetch()){
            $params['forms_staff_auth']['site_id'][$row['site_id']] = $row['site_id'];
            if($row['role_id'] != NULL){
                $params['forms_staff_auth']['role_id'][$row['site_id']] = $row['role_id'];
                $params['forms_staff_auth']['auth_mode'][$row['site_id']] = 'role';
            }
            elseif($row['auth_cd'] != NULL){
                $params['forms_staff_auth']['auth_cd'][$row['site_id']][] = $row['auth_cd'];
                $params['forms_staff_auth']['auth_mode'][$row['site_id']] = 'auth';
            }
        }
    }
    $staff = new Model_Staff();
    $arr_auth = $staff->getAuth();
    
    $role = array();
    $plugin = array();
    
    if(isset($params['forms_staff_auth']['site_id']))
    {
        foreach($params['forms_staff_auth']['site_id'] as $site_id)
        {
            //ロール選択
            $db->query(sprintf("SELECT * FROM M_ROLE WHERE site_id = '%u' AND enabled = 1 ORDER BY id ASC", (int)$site_id));
            while($res = $db->fetch()){
                $role_id = $res['id'];
                $tmp = array('value' => $role_id, 'name' => $res['name']. ($res['actived']!=1?'(停止中)':''));
                if(isset($params['forms_staff_auth']['role_id'][$site_id]) and
                   $role_id == $params['forms_staff_auth']['role_id'][$site_id])
                {
                    $tmp['selected'] = '1';
                }
                $role[$site_id][] = $tmp;
            }

            //個別選択(プラグイン)
            $db->query(sprintf("SELECT * FROM D_SITE_PLUGIN WHERE site_id = '%u' ORDER BY auth_cd ASC", (int)$site_id));
            while($res = $db->fetch()){
                $auth_cd = $res['auth_cd'];
                $img_file_name = explode(' ', strtolower($arr_auth[$auth_cd]));
                $tmp = array('value' => $auth_cd, 'name' => $arr_auth[$auth_cd], 'img_file_name' => $img_file_name[0]);
                if(isset($params['forms_staff_auth']['auth_cd'][$site_id]) and
                   is_array($params['forms_staff_auth']['auth_cd'][$site_id]) and
                   in_array($auth_cd, $params['forms_staff_auth']['auth_cd'][$site_id]))
                {
                    $tmp['checked'] = '1';
                }
                $plugin[$site_id][] = $tmp;
            }
        }
    }
    $smarty->assign('role', $role);
    $smarty->assign('plugin', $plugin);
    $smarty->assign('id', $id);
    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params['forms']);
    $smarty->assign('forms_staff_auth', $params['forms_staff_auth']);
    $smarty->display('staff/staff_form.html');
}

function exec_validate_edit_form(&$params, &$smarty, &$staff)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    if ($params['mode'] == 'delete')
    {
        return exec_delete_form($params, $smarty, $staff);
    }
    $params['forms']['id'] = $params['id'];
    $err = array();
    if ($staff->validate($params['forms'], $err)){
        return exec_edit_form($params, $smarty, $staff);
    }
    $validate = new Model_Validate();
    $smarty->assign('validate', $validate);
    $smarty->assign('err', $err);
    return 'edit';
}
function exec_edit_form(&$params, &$smarty, &$staff)
{
    $id = $params['id'];
    if($_POST['mode'] == "delete"){
        $params['forms']['enabled'] = 0;
    }
    if(!isset($params['forms']['actived'])){
        $params['forms']['actived'] = 1;
    }
    if(!isset($params['forms']['admin_flg'])){
        $params['forms']['admin_flg'] = 0;
    }
    if(empty($params['forms']['image_file'][0])){
        $params['forms']['image_file'] = '';
    }
    elseif(preg_match('/^http/', $params['forms']['image_file'][0])){
        unset($params['forms']['image_file']);
    }
    else{
        $tmp_image_file = $params['forms']['image_file'];
        unset($params['forms']['image_file']);
    }
    $staff->update($id, $params['forms']);
    //画像
    if(isset($tmp_image_file)){
        $uploader  = new Model_Uploader();
        $cache     = $tmp_image_file[0];
        $base_name = 'image_'.$id;
        $move_to   = $staff->getStaffImageDir();
        $filename  = $uploader->moveCacheImage($cache, $move_to, $base_name);
        $data = array();
        $data['image_file'] = $filename;
        $staff->update($id, $data);
    }
    //権限
    if(isset($params['forms_staff_auth'])){
        auth_register($id, $params['forms_staff_auth']);
    }
    else{
        auth_register($id);
    }
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=edit_complete&id=' . $id);
    exit();
}
function op_edit_complete($params, &$smarty, &$staff)
{
    $smarty->assign('phase', 'complete');
    if(isset($params['id'])){
        $smarty->assign('id', $params['id']);
        $smarty->assign('forms', array('id' => $params['id']));
    }
    $smarty->assign('message', '更新が完了しました');
    $smarty->display('staff/staff_form.html');
}
function exec_delete_form(&$params, &$smarty, &$staff)
{
    $id = $params['id'];
    $params['data']['enabled'] = 0;
    $staff->update($id, $params['data']);
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=delete_complete&id=' . $id);
    exit();
}
function op_delete_complete($params, &$smarty, &$staff)
{
    $smarty->assign('phase', 'complete');
    $smarty->assign('message', '削除が完了しました');
    $smarty->display('staff/staff_form.html');
}

function op_get_auth($params, &$smarty, &$staff)
{
    $db = new Model_DB();
    $arr_auth = $staff->getAuth();

    if(isset($params['mode']) && $params['mode'] == 'plugin' && isset($params['site_id'])){

        $db->query(sprintf("SELECT * FROM D_SITE_PLUGIN WHERE site_id = '%u' ORDER BY auth_cd ASC", (int)$params['site_id']));
        $plugin = array();
        while($res = $db->fetch()){
            $cd = $res['auth_cd'];
            $plugin[] = array('value' => $cd, 'name' => $arr_auth[$cd]);
        }
        echo(json_encode($plugin));
        exit();
    }
    elseif(isset($params['mode']) && $params['mode'] == 'role' && isset($params['site_id'])){

        $db->query(sprintf("SELECT * FROM M_ROLE WHERE site_id = '%u' AND enabled = 1 ORDER BY id ASC", (int)$params['site_id']));
        $role = array();
        while($res = $db->fetch()){
            $id = $res['id'];
            $role[] = array('value' => $id, 'name' => $res['name']. ($res['actived']!=1?'(停止中)':''));
        }
        //var_dump($role);exit;
        $db->query(sprintf("SELECT * FROM D_SITE_PLUGIN WHERE site_id = '%u' ORDER BY auth_cd ASC", (int)$params['site_id']));
        $plugin = array();
        while($res = $db->fetch()){
            $cd = $res['auth_cd'];
            $plugin[] = array('value' => $cd, 'name' => $arr_auth[$cd]);
        }
        echo(json_encode(array('role' => $role, 'plugin' => $plugin)));
        exit();
    }
}

// 権限登録・更新
function auth_register($id, $auth = '')
{
    $db = new Model_DB();

    $sql = sprintf( "DELETE FROM D_STAFF_AUTH WHERE staff_id = %u", $id );
    $db->query( $sql );
    
    if($auth != '')
    {
        foreach($auth['site_id'] as $sid){
            if($auth['auth_mode'][$sid]=='role' && isset($auth['role'][$sid])){
                $sql = sprintf("INSERT INTO D_STAFF_AUTH (staff_id,site_id,role_id) VALUES ('%u','%u','%u')", $id, $sid, $auth['role'][$sid]);
                $db->query($sql);
                //echo $sql."<br/>";
            }
            elseif($auth['auth_mode'][$sid]=='auth' && isset($auth['auth'][$sid])){
                foreach($auth['auth'][$sid] as $code){
                    $sql = sprintf("INSERT INTO D_STAFF_AUTH (staff_id,site_id,auth_cd) VALUES ('%u','%u','%s')", $id, $sid, $db->escape($code));
                    $db->query($sql);
                    //echo $sql."<br/>";
                }
            }
        }
    }
}


//共通で使えるものだが、とりあえず
function op_picture()
{
    header("Content-Type: image/*");
    readfile( TEMPORARY_DIR . $_GET['file']);
}

?>